package com.arpa.ntocc.common.common.util;

import com.arpa.ntocc.common.common.constant.StrConsts;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 日志记录工具类
 * @Author liuyj
 * @Date 2019-11-18 18:48:54
 */
@Log4j2
public class LogUtil {

    /**
     * 记录日志
     * @param type 类型
     * @param result 结果
     * @param desc 描述
     * @return
     */
    public static String log(String loginName, String type, String result, String desc){
        HttpServletRequest request = HttpUtil.getRequest();
        String returnStr="";
        String deviceId = "";
        String ip= "";
        String allUrl= "";
        String method= "";
        String postParams= "";
        try {
            if(request!=null){
                //请求ip
                ip = HttpUtil.getIpAddress(request);
                //设备id
                deviceId=getDeviceId(request);
                //请求路径
                allUrl=getRequestUrl(request);
                //请求方式GET，POST
                method = request.getMethod();
            }
            //获取登录用户账号
            if(StringUtils.isBlank(loginName)){
                loginName = UserUtil.getLoginName();
            }
            //处理类型
            type = StringUtils.isBlank(type)?"":type;
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
        }
        returnStr += ip+"|"+deviceId+"|"+loginName+"|"+method+"|"+type+"|"+allUrl+"|"+postParams+"|"+result+"|"+desc;
        return returnStr;
    }

    /**
     * 记录日志
     * @return
     */
    public static String log(){
        return log("","","","");
    }

    /**
     * 记录日志
     * @param desc
     * @return
     */
    public static String log(String desc){
        return log("","","",desc);
    }

    /**
     * 记录日志
     * @param type
     * @param desc
     * @return
     */
    public static String log(String type, String desc){
        return log("",type,"",desc);
    }

    /**
     * 记录日志
     * @param type
     * @param result
     * @param desc
     * @return
     */
    public static String log(String type, String result, String desc){
        return log("",type,result,desc);
    }

    /**
     * 获取请求路径加参数
     * @param request
     * @return
     */
    private static String getRequestUrl(HttpServletRequest request) {
        String url="";
        String uri=request.getRequestURI();
        String queryStr=request.getQueryString();
        if(StringUtils.isNotBlank(queryStr)){
            url = uri+"?"+queryStr;
        }else{
            url = uri ;
        }
        return url;
    }

    /**
     * 获取设备id
     * @param request
     * @return
     */
    private static String getDeviceId(HttpServletRequest request) {
        String deviceId = request.getHeader("deviceId");
        return deviceId;
    }

}
